package com.xylx.interview.loadbalance;

import java.util.HashMap;
import java.util.Map;

/**
 * 加权轮询算法
 * 实际中可能遇到某个服务器压力较大，长时间执行。
 */
public class WeightPollServer {

    public static Map<String, Integer> map = new HashMap<>();

    static {
        map.put("10.180.11.126:8888", 2);
        map.put("10.180.11.128:8888", 7);
        map.put("10.180.11.130:8888", 5);
        map.put("10.180.11.131:8888", 9);
    }

    static int index;

    public static String getServer() {
        int weight = map.values().stream().mapToInt(p -> p).sum();
        int number = (index++) % weight;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue() >= number) {
                return entry.getKey();
            }
            number = number - entry.getValue();
        }

        return "";
    }

    public static void main(String[] args) {
        for (int i = 0; i < 15; i++) {
            System.out.println(getServer());
        }
    }
}